import axios from 'axios'
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
import { Message, Modal } from '@arco-design/web-vue'
import { useUserStore } from '@/store'
import { getToken } from '@/utils/auth'
import qs from 'query-string'

export interface HttpResponse<T = unknown> {
	status: number

	msg: string

	code: number

	data: T
}

if (import.meta.env.VITE_API_BASE_URL) {
	axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL
}

axios.interceptors.request.use(
	(config: AxiosRequestConfig) => {
		// 只针对get方式进行序列化
		if (config.method === 'get') {
			config.paramsSerializer = params => {
				return qs.stringify(params,
					{ arrayFormat: 'separator' })
			}
		}
		// let each request carry token
		// this example using the JWT token
		// Authorization is a custom headers key
		// please modify it according to the actual situation
		const token = getToken()
		if (token) {
			if (!config.headers) {
				config.headers = {}
			}
			config.headers.Authorization = `Bearer ${token}`
		}
		return config
	},
	(error) => {
		// do something
		return Promise.reject(error)
	}
)
// 添加响应拦截器
axios.interceptors.response.use(
	(response: AxiosResponse<HttpResponse>) => {
		const res = response.data
		// 如果自定义代码不是20000，则判定为错误。
		if (res.code !== 200) {
			Message.error({
				content: res.msg || 'Error',
				duration: 5 * 1000,
			})
			// 50008：非法令牌;50012：其他客户端已登录;50014：令牌过期;
			if (
				[50008, 50012, 50014].includes(res.code) &&
				response.config.url !== '/api/user/info'
			) {
				Modal.error({
					title: 'Confirm logout',
					content: '您已被注销，您可以取消以留在此页面上，或重新登录',
					okText: 'Re-Login',
					async onOk() {
						const userStore = useUserStore()
						await userStore.logout()
						window.location.reload()
					},
				})
			}
			return Promise.reject(new Error(res.msg || 'Error'))
		}
		return res
	},
	(error) => {
		Message.error({
			content: error.response.data.msg || error.response.data.errors[0].defaultMessage || 'Request Error',
			duration: 5 * 1000,
		})
		return Promise.reject(error)
	}
)
